package cn.com.ddapp.ddm.ui;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Login;
import cn.com.ddapp.ddm.bean.mine.UserData;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.pay.wx.Constants;
import cn.com.ddapp.ddm.util.LoadingDialog;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.util.TLog;
import cn.com.ddapp.ddm.util.TextUtil;
import cn.com.ddapp.ddm.widget.TipsToast;
import okhttp3.Call;


/**
 * Created by Administrator on 2016/7/29 0029.
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.welcome)
	TextView welcome;
	@BindView(R.id.register)
	TextView register;
	@BindView(R.id.forget_pwd)
	TextView forget_pwd;
	@BindView(R.id.email)
	EditText email;
	@BindView(R.id.pwd)
	EditText pwd;
    @BindView(R.id.other_loginll)
    LinearLayout other_loginll;
    private UMShareAPI umShareAPI;
    private String qUserName,qName,qHeadimg;
    private IWXAPI api;
    public static final String ACTION_NAME ="wechatlogin";
    private String pushId = "android/"+ BaseApplication.context().getRegistrationId();

	@Override
	public void initView() {

        if(TDevice.isTablet(LoginActivity.this)){
            other_loginll.setVisibility(View.GONE);
        }else{
            other_loginll.setVisibility(View.VISIBLE);
        }
        initWeiXin();
		setTitle(R.string.login);
		setTitleLeftImg(R.mipmap.back_icon);
		TextUtil.setFlags(welcome);
		TextUtil.setFlags(register);
		TextUtil.setFlags(forget_pwd);
//        PlatformConfig.setQQZone("100424468","c7394704798a158208a74ab60104f0ba");
        umShareAPI = UMShareAPI.get(this);
	}

    private void initWeiXin() {
        api = WXAPIFactory.createWXAPI(mContext, Constants.APP_ID,false);
        api.registerApp(Constants.APP_ID);
    }

    @Override
	public void initData() {

	}

	@Override
	public int getContentViewId() {
		return R.layout.login_main;
	}

	@Override
	protected String getFragmentTag() {
		return null;
	}

	private void reequestData() {
		final OkUtilCallback okUtilCallback = new OkUtilCallback() {
			@Override
			public void onMyResponse(String response, int id) {
//				TLog.log(getFragmentTag(), response);
				Login entity = gson.fromJson(response, Login.class);
				if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) && entity.getLogin()) {
				} else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
					BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
				} else if ((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
					//登录成功操作
					SPUtils.setStringData(LoginActivity.this, SPUtils.USERID, String.valueOf(entity.getUserId()));
					SPUtils.setBooleanData(LoginActivity.this, SPUtils.ISLOGIN, true);
					SPUtils.setStringData(LoginActivity.this, SPUtils.EMAIL, email.getText().toString());
                    BaseApplication.showToast("登陆成功");
                    AppConfig.isRefreshShocpar = true;
					setResult(0x86);
					finish();
				}
			}

			@Override
			public void onError(Call call, Exception e, int id) {
				super.onError(call, e, id);
				BaseApplication.getIntstance().showToast(R.string.network_error, Toast.LENGTH_SHORT, 0, Gravity.CENTER);
			}
		};
		OKUtilAPI.post(OKUtilAPI.login, "userName=" + email.getText().toString() + "&pwd=" + pwd.getText().toString()+"&pushId=" + pushId, okUtilCallback);
	}
    //QQ
    private UMAuthListener umAuthListener=new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int i, Map<String, String> map) {
            umShareAPI.getPlatformInfo(LoginActivity.this, platform, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
                    Set<String> set = data.keySet();
//                    Log.i("aaa","--info--"+data.get("screen_name").toString()+"--"+data.get("profile_image_url").toString()+"--"+data.get("openid").toString());
                   qUserName=data.get("openid").toString();
                   qName=data.get("screen_name").toString();
                    qHeadimg=data.get("profile_image_url").toString();
                    toQQLogin(qUserName,qName,qHeadimg);
                    for (String string : set) {
                        String str = data.get(string);
//                        Log.i("aaa","--info--"+string);
                    }

                }
                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    Log.i("aaa","---error--");
                }
                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    Log.i("aaa","---onCancel--");
                }
            });
            LoadingDialog.clossDialog();
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            Log.i("aaa","---onError--");
            LoadingDialog.clossDialog();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            Log.i("aaa","---onC2ancel--");
            LoadingDialog.clossDialog();
        }
    };
//WECAHT
    private UMAuthListener wAuthListener=new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int i, Map<String, String> map) {
            umShareAPI.getPlatformInfo(LoginActivity.this, platform, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
                    String openid=data.get("openid");
                    String nickName=data.get("screen_name");
                    String headimgUrl=data.get("profile_image_url");
//                    Log.i("aaa","--openid--"+openid+"--"+nickName+"--"+headimgUrl);
                    Set<String> set = data.keySet();
                    toWECHATLogin(openid,nickName,headimgUrl);

                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    Log.i("aaa","---error--");
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    Log.i("aaa","---onCancel--");
                }
            });
            LoadingDialog.clossDialog();
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            Log.i("aaa","---onError--");
            LoadingDialog.clossDialog();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            Log.i("aaa","---onC2ancel--");
            LoadingDialog.clossDialog();
        }
    };

    //微信登录
    private void toWECHATLogin(String openid, String nickName, String headimgUrl) {
        try {
        LoadingDialog.showDialog(LoginActivity.this,"正在登录中...",true);
        final OkUtilCallback okUtilCallback = new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
                UserData entity = gson.fromJson(response, UserData.class);
                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) && entity.getLogin()) {
                } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    //登录成功操作
                    SPUtils.setStringData(LoginActivity.this, SPUtils.USERID, String.valueOf(entity.getUser().getId()));
                    SPUtils.setBooleanData(LoginActivity.this, SPUtils.ISLOGIN, true);
                    SPUtils.setStringData(LoginActivity.this, SPUtils.EMAIL, entity.getUser().getName());
                    BaseApplication.showToast("登陆成功");
                    AppConfig.isRefreshShocpar = true;
                    setResult(0x86);
                    finish();
                }
                LoadingDialog.clossDialog();

            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                BaseApplication.getIntstance().showToast(R.string.network_error, Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                LoadingDialog.clossDialog();

            }
        };
        OKUtilAPI.post(OKUtilAPI.otherLogin, "username=" + openid + "&name=" + URLEncoder.encode(nickName, "utf-8")+"&headImg="+headimgUrl, okUtilCallback);
        }catch (Exception e){
            e.printStackTrace();
        }
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        umShareAPI.onActivityResult(requestCode, resultCode, data);
        if(resultCode==-1){
        }
         Log.i("aaa", resultCode + "");
    }

    private void toQQLogin(String uname,String name,String headimg) {
        try {
        LoadingDialog.showDialog(LoginActivity.this,"正在登录中...",true);
        final OkUtilCallback okUtilCallback = new OkUtilCallback() {
            @Override
            public void onMyResponse(String response, int id) {
//				TLog.log(getFragmentTag(), response);
                UserData entity = gson.fromJson(response, UserData.class);
                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) && entity.getLogin()) {
                } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {

                    //登录成功操作
                    SPUtils.setStringData(LoginActivity.this, SPUtils.USERID, String.valueOf(entity.getUser().getId()));
                    SPUtils.setBooleanData(LoginActivity.this, SPUtils.ISLOGIN, true);
                    SPUtils.setStringData(LoginActivity.this, SPUtils.EMAIL, entity.getUser().getName());
                    AppConfig.isRefreshShocpar = true;
                    BaseApplication.showToast("登陆成功");
                    setResult(0x86);
                    finish();
                }
                LoadingDialog.clossDialog();

            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                BaseApplication.getIntstance().showToast(e.getMessage().toString(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                LoadingDialog.clossDialog();

            }
        };
        OKUtilAPI.post(OKUtilAPI.otherLogin, "username=" + uname + "&name=" + URLEncoder.encode(name, "utf-8")+"&headImg="+headimg, okUtilCallback);
        }catch (Exception e){
            e.printStackTrace();
        }
        }

    @OnClick({R.id.logon_btn, R.id.register, R.id.forget_pwd,R.id.qqlogin,R.id.wechatlogin})
	void onclick(View v) {
		switch (v.getId()) {
			case R.id.register:
				Intent intent = new Intent(this, RegisterActivity.class);
				startActivity(intent);
				break;

			case R.id.forget_pwd:
				Intent intent2 = new Intent(this, ForgetPwdActivity.class);
				startActivity(intent2);
				break;

			case R.id.logon_btn:

				if (!NetUtils.isConnected(LoginActivity.this)) {
					TipsToast.makeText(LoginActivity.this, R.string.tip_network_error, TipsToast.LENGTH_SHORT).show();
				} else {
					if (TextUtils.isEmpty(email.getText().toString().trim())) {
						TipsToast.makeText(LoginActivity.this, R.string.email_is_null, TipsToast.LENGTH_SHORT).show();
						return;
					}
					if (TextUtils.isEmpty(pwd.getText().toString().trim())) {
						TipsToast.makeText(LoginActivity.this, R.string.pwd_is_null, TipsToast.LENGTH_SHORT).show();
						return;
					}

					reequestData();
//					APIRetrofit.getRetrofit()
//							.create(APIService.class)
//							.login(email.getText().toString(), pwd.getText().toString())
//							.subscribeOn(Schedulers.io())
//							.observeOn(AndroidSchedulers.mainThread())
//							.unsubscribeOn(Schedulers.io())
//							.subscribe(new Subscriber<Login>() {
//								@Override
//								public void onCompleted() {
//
//								}
//
//								@Override
//								public void onError(Throwable e) {
//									TipsToast.makeText(LoginActivity.this, R.string.network_error, TipsToast.LENGTH_SHORT).show();
//								}
//
//								@Override
//								public void onNext(Login login) {
//									if (login.getResult().equals("OK")) {
//										TipsToast.makeText(LoginActivity.this, R.string.successful_login, TipsToast.LENGTH_SHORT).show();
//
//										SPUtils.setStringData(LoginActivity.this, SPUtils.USERID, String.valueOf(login.getUserId()));
//										SPUtils.setStringData(LoginActivity.this, SPUtils.USERTYPE, String.valueOf(login.getType()));
//										SPUtils.setBooleanData(LoginActivity.this, SPUtils.ISLOGIN, true);
//
//										setResult(0x87);
//										finish();
//
//									} else {
//										TipsToast.makeText(LoginActivity.this, login.getResult(), TipsToast.LENGTH_SHORT).show();
//									}
//
//								}
//							});

				}
				break;
            case R.id.qqlogin:
                LoadingDialog.showDialog(LoginActivity.this,"正在打开QQ...",true);
                SHARE_MEDIA platform = SHARE_MEDIA.QQ;//此处是QQ授权
                umShareAPI.doOauthVerify(this, platform, umAuthListener);
                break;
            case R.id.wechatlogin:
                LoadingDialog.showDialog(LoginActivity.this,"正在打开微信...",true);
                SHARE_MEDIA wplatform = SHARE_MEDIA.WEIXIN;
                umShareAPI.doOauthVerify(this, wplatform, wAuthListener);
                break;
		}
	}

}
